import _ from 'lodash';
import log4js from 'log4js';
import config from 'config';
import fs from 'fs';
import path from 'path';

// Ensure logs directory exists
const LOGS_DIR = './logs';
if (!fs.existsSync(LOGS_DIR)) {
  fs.mkdirSync(LOGS_DIR, { recursive: true });
}

const LOG4JS = {
  appenders: { console: { type: 'console' } },
  categories: { default: { appenders: ['console'], level: config.get('logger.level') } },
  pm2: true,
};

const cacheOfLoggers = new Map();

export default {
  getLogger: (name) => {
    if (!name || typeof name !== 'string') {
      throw new Error('Logger name must be a non-empty string');
    }

    if (cacheOfLoggers.has(name)) {
      return cacheOfLoggers.get(name);
    }

    try {
      const appenders = { console: { type: 'console' } };
      const categories = {};

      // Create file appender with proper path
      const logFileName = `${name}.log`;
      const logFilePath = path.join(LOGS_DIR, logFileName);

      appenders[name] = {
        type: 'file',
        filename: logFilePath,
        maxLogSize: 10 * 1024 * 1024, // 10MB
        backups: 5,
        compress: true
      };

      categories[name] = {
        appenders: [name, 'console'],
        level: config.get('logger.level') || 'debug'
      };

      log4js.configure(_.defaultsDeep(LOG4JS, { appenders, categories }));
      const logger = log4js.getLogger(name);

      cacheOfLoggers.set(name, logger);
      return logger;
    } catch (error) {
      console.error(`Failed to create logger for ${name}:`, error);
      // Fallback to console logger
      return log4js.getLogger();
    }
  },

  // Method to clear cache if needed
  clearCache: () => {
    cacheOfLoggers.clear();
  },

  // Method to get all cached logger names
  getCachedLoggers: () => {
    return Array.from(cacheOfLoggers.keys());
  }
};
